const Router = require('koa-router');
const { pool } = require('../config/db');
const authMiddleware = require('../middleware/auth');

const router = new Router({ prefix: '/tags' });

// 后台：创建标签（支持重复检测和输入验证）
router.post('/', authMiddleware, async (ctx) => {
  try {
    // 获取并验证标签名称
    const { name } = ctx.request.body;

    // 参数验证
    if (!name || typeof name !== 'string') {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '参数错误：标签名称不能为空',
        code: 400
      };
      return;
    }

    // 清理和标准化标签名称
    const trimmedName = name.trim();

    // 验证标签名称长度
    if (trimmedName.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '参数错误：标签名称不能为空字符串',
        code: 400
      };
      return;
    }

    if (trimmedName.length > 20) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '参数错误：标签名称长度不能超过20个字符',
        code: 400
      };
      return;
    }

    // 验证标签名称格式（只允许中文、英文、数字和连字符）
    const namePattern = /^[\u4e00-\u9fa5a-zA-Z0-9\-]+$/;
    if (!namePattern.test(trimmedName)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '参数错误：标签名称只能包含中文、英文、数字和连字符',
        code: 400
      };
      return;
    }

    // 检查标签是否已存在（不区分大小写）
    const [existingTags] = await pool.query(
      'SELECT id FROM tags WHERE LOWER(name) = LOWER(?)',
      [trimmedName]
    );

    if (existingTags.length > 0) {
      ctx.status = 409; // Conflict
      ctx.body = {
        success: false,
        message: '标签已存在',
        data: { id: existingTags[0].id },
        code: 409
      };
      return;
    }

    // 创建新标签
    const [result] = await pool.query(
      'INSERT INTO tags (name, count) VALUES (?, 0)',
      [trimmedName]
    );

    // 返回成功响应
    ctx.status = 201;
    ctx.body = {
      success: true,
      message: '标签创建成功',
      data: {
        id: result.insertId,
        name: trimmedName,
        count: 0
      },
      code: 200
    };

  } catch (error) {
    console.error('创建标签失败:', error);

    // 处理数据库唯一约束冲突
    if (error.code === 'ER_DUP_ENTRY') {
      ctx.status = 409;
      ctx.body = {
        success: false,
        message: '标签已存在',
        code: 409
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '服务器内部错误，请稍后重试',
        code: 500
      };
    }
  }
});

// 后台：通过ID更新标签
router.put('/:id', authMiddleware, async (ctx) => {
  try {
    const { id } = ctx.params;
    const { name } = ctx.request.body;

    // 参数验证 - 标签ID
    const tagId = parseInt(id);
    if (isNaN(tagId) || tagId <= 0) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：无效的标签ID',
        code: 400
      };
    }

    // 输入验证 - 标签名称
    if (!name || typeof name !== 'string') {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：标签名称(name)不能为空',
        code: 400
      };
    }

    // 清理和标准化标签名称
    const trimmedName = name.trim();

    // 验证标签名称长度
    if (trimmedName.length === 0) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：标签名称不能为空字符串',
        code: 400
      };
    }

    if (trimmedName.length > 20) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：标签名称长度不能超过20个字符',
        code: 400
      };
    }

    // 验证标签名称格式（只允许中文、英文、数字和连字符）
    const namePattern = /^[\u4e00-\u9fa5a-zA-Z0-9\-]+$/;
    if (!namePattern.test(trimmedName)) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：标签名称只能包含中文、英文、数字和连字符',
        code: 400
      };
    }

    // 检查标签是否存在
    const [existingTag] = await pool.query(
      'SELECT id, name FROM tags WHERE id = ?',
      [tagId]
    );

    if (existingTag.length === 0) {
      ctx.status = 404;
      return ctx.body = {
        success: false,
        message: '标签不存在',
        code: 404
      };
    }

    // 如果新名称与旧名称相同，直接返回成功
    if (existingTag[0].name.toLowerCase() === trimmedName.toLowerCase()) {
      ctx.body = {
        success: true,
        message: '标签更新成功',
        data: {
          id: tagId,
          name: trimmedName,
          changed: false
        },
        code: 200
      };
      return;
    }

    // 检查新名称是否与其他标签冲突（不区分大小写）
    const [conflictingTags] = await pool.query(
      'SELECT id FROM tags WHERE LOWER(name) = LOWER(?) AND id != ?',
      [trimmedName, tagId]
    );

    if (conflictingTags.length > 0) {
      ctx.status = 409; // Conflict
      return ctx.body = {
        success: false,
        message: '标签名称已存在',
        code: 409
      };
    }

    // 更新标签名称
    const [updateResult] = await pool.query(
      'UPDATE tags SET name = ? WHERE id = ?',
      [trimmedName, tagId]
    );

    // 检查是否真的有记录被更新
    if (updateResult.affectedRows === 0) {
      ctx.status = 404;
      return ctx.body = {
        success: false,
        message: '标签更新失败',
        code: 404
      };
    }

    // 返回成功响应
    ctx.body = {
      success: true,
      message: '标签更新成功',
      data: {
        id: tagId,
        name: trimmedName,
        changed: true
      },
      code: 200
    };

  } catch (error) {
    console.error('更新标签失败:', error);

    // 处理数据库唯一约束冲突
    if (error.code === 'ER_DUP_ENTRY') {
      ctx.status = 409;
      return ctx.body = {
        success: false,
        message: '标签名称已存在',
        code: 409
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '服务器内部错误，请稍后重试',
        code: 500
      };
    }
  }
});

// 后台：删除标签（只接收数组）
router.delete('/', authMiddleware, async (ctx) => {
  try {
    const requestBody = ctx.request.body;
    console.log('requestBody:', requestBody);

    // 只接收数组格式
    let targetIds = [];

    // 1. 优先检查直接数组格式：[123, 456, 789]
    if (Array.isArray(requestBody)) {
      targetIds = requestBody;
    }
    // 2. 检查 {ids: [...]} 格式
    else if (requestBody && requestBody.ids && Array.isArray(requestBody.ids)) {
      targetIds = requestBody.ids;
    } else if (typeof requestBody.ids === 'string') {
      targetIds.push(requestBody.ids);
    }
    // 3. 其他情况都视为无效参数
    else {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：请提供标签ID数组',
        code: 400
      };
    }

    // 验证数组不能为空
    if (targetIds.length === 0) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：标签ID数组不能为空',
        code: 400
      };
    }

    // 转换并验证所有ID（确保都是数字）
    const validIds = [];
    for (const id of targetIds) {
      const tagId = parseInt(id);
      if (isNaN(tagId) || tagId <= 0) {
        ctx.status = 400;
        return ctx.body = {
          success: false,
          message: `参数错误：无效的标签ID ${id}`,
          code: 400
        };
      }
      validIds.push(tagId);
    }

    // 检查标签是否存在和使用情况
    const placeholders = validIds.map(() => '?').join(',');

   // 检查标签是否存在（修改查询，包含使用统计）
    const [existingTags] = await pool.query(
      `SELECT t.id, t.name, 
              (SELECT COUNT(*) FROM article_tags at WHERE at.tag_id = t.id) as usage_count
       FROM tags t 
       WHERE t.id IN (${placeholders})`,
      validIds
    );

    // 检查是否有标签被使用
    const usedTags = existingTags.filter(tag => tag.usage_count > 0);
    if (usedTags.length > 0) {
      ctx.status = 409;
      return ctx.body = {
        success: false,
        message: '部分标签正在被文章使用，无法删除',
        data: {
          usedTags: usedTags.map(tag => ({
            id: tag.id,
            name: tag.name,
            usageCount: tag.usage_count
          }))
        },
        code: 409
      };
    }

    // 开始事务处理
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 1. 删除关联表中的记录（虽然usage_count为0，但做双重保险）
      await connection.query(
        `DELETE FROM article_tags WHERE tag_id IN (${placeholders})`,
        validIds
      );

      // 2. 删除标签
      const [deleteResult] = await connection.query(
        `DELETE FROM tags WHERE id IN (${placeholders})`,
        validIds
      );

      await connection.commit();

      // 返回成功响应...
      ctx.body = {
        success: true,
        message: `成功删除 ${deleteResult.affectedRows} 个标签`,
        data: {
          deletedCount: deleteResult.affectedRows,
          deletedIds: validIds
        },
        code: 200
      };

    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }

  } catch (error) {
    console.error('删除标签失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '服务器内部错误，请稍后重试',
      code: 500
    };
  }
});

// 后台：获取所有标签+搜索
router.get('/', authMiddleware, async (ctx) => {
  try {
    // 获取查询参数
    const { keyword, page = 1, pageSize = 10 } = ctx.query;

    // 参数验证
    const pageNum = parseInt(page);
    const limitNum = parseInt(pageSize);

    if (isNaN(pageNum) || pageNum < 1) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：页码必须是正整数',
        code: 400
      };
    }

    if (isNaN(limitNum) || limitNum < 1 || limitNum > 100) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：每页条数必须在1-100之间',
        code: 400
      };
    }

    const offset = (pageNum - 1) * limitNum;
    let total = 0;
    let rows = [];

    // 判断是否有关键词搜索
    const hasKeyword = keyword && typeof keyword === 'string' && keyword.trim() !== '';

    if (hasKeyword) {
      // 有关键词：进行模糊搜索
      const trimmedKeyword = keyword.trim();
      const searchCondition = `%${trimmedKeyword}%`;

      // 查询总数（带搜索条件）
      const [countResult] = await pool.query(
        'SELECT COUNT(*) as total FROM tags WHERE name LIKE ?',
        [searchCondition]
      );
      total = countResult[0].total;

      // 如果总数大于0，查询分页数据
      if (total > 0) {
        const [searchRows] = await pool.query(
          'SELECT id, name, count FROM tags WHERE name LIKE ? ORDER BY count DESC, id ASC LIMIT ? OFFSET ?',
          [searchCondition, limitNum, offset]
        );
        rows = searchRows;
      }
    } else {
      // 无关键词：获取所有标签
      // 查询总数（不带搜索条件）
      const [countResult] = await pool.query('SELECT COUNT(*) as total FROM tags');
      total = countResult[0].total;

      // 如果总数大于0，查询分页数据
      if (total > 0) {
        const [allRows] = await pool.query(
          'SELECT id, name, count FROM tags ORDER BY count DESC, id ASC LIMIT ? OFFSET ?',
          [limitNum, offset]
        );
        rows = allRows;
      }
    }

    // 格式化数据（去除名称前后空格）
    const formattedRows = rows.map(tag => ({
      ...tag,
      name: tag.name.trim()
    }));

    // 计算总页数
    const totalPages = total > 0 ? Math.ceil(total / limitNum) : 0;

    // 返回成功响应
    ctx.body = {
      success: true,
      message: hasKeyword ? '标签搜索成功' : '标签列表获取成功',
      data: {
        list: formattedRows,
        total: total,
        page: pageNum,
        pageSize: limitNum,
        totalPages: totalPages
      },
      code: 200
    };

  } catch (error) {
    console.error('获取标签列表失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '服务器内部错误，请稍后重试',
      code: 500
    };
  }
});

module.exports = router;